// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

export default class Subscribe {
    constructor(eventNames) {
        this._events = {};
        (eventNames || []).forEach(name => {
            this._events[name] = [];
        });
    }

    trigger(eventName, data) {
        let events = this._events[eventName];
        events && events.forEach(fn => {
            fn && fn.call(this, {name: eventName}, data);
        });
    }
    
    on(eventName, callback) {
        if (eventName in this._events) {
            this._events[eventName].push(callback);
        }
    }
    
    off(eventName, callback) {
        let events = this._events[eventName];
        if (events && callback) {
            for (let idx = events.length - 1; idx >= 0; idx--) {
                if (events[idx] === callback) {
                    events.splice(idx, 1);
                }
            }
        }
    }
}
